package com.kafka.producer;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;

import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.kafka.bean.Iccard;
import com.kafka.bean.SaleDetail;
import com.kafka.bean.resultmap.SaleDetailResultMap;
import com.kafka.common.Constant;
import com.kafka.common.String.StringValues;
import com.kafka.core.BaseProducer;
import com.kafka.dao.IccardMapper;
import com.kafka.dao.SaleDetailMapper;
import com.kafka.enumtype.MsgType;
import com.kafka.enumtype.ResponseType;
import com.kafka.producer.inter.IProducer;
import com.kafka.util.BaseUtil;
import com.kafka.valid.PayValid;

/**
 * 消费消息类
 * 
 * @author leihongan
 * 
 */
public class PayProducer extends BaseProducer implements IProducer {
	IccardMapper iccardDao = sqlSession.getMapper(IccardMapper.class);
	SaleDetailMapper saleDetailDao = sqlSession.getMapper(SaleDetailMapper.class);
	private final Producer<String, String> producer;
	private static String serialnum;
	public String TOPIC;

	public PayProducer() {
		Properties properties = new Properties();
		try {
			properties.load(ClassLoader
					.getSystemResourceAsStream("pay.properties"));
			TOPIC = properties.getProperty("topic");
		} catch (IOException e) {
			e.printStackTrace();
		}
		producer = new Producer<String, String>(new ProducerConfig(properties));
	}

	public String produce(JSONObject message) {
		if (MsgType.pay.toString().equals(message.getString("msgtype"))){
			return payProduce(message);
		} else if (MsgType.RECHARGE.toString().equals(message.getString("msgtype"))) {
			return rechargeProduce(message);
		} else {
			return null;
		}
	}

	/**
	 * 支付处理
	 * @param message
	 * @return
	 */
	private String payProduce(JSONObject message) {
		Map<String, Object> properties = new HashMap<>();
		properties.put("status", Constant.SUCCESS);
		properties.put("message_id", message.get("msgid"));
		if (messageDao.selectByParam(properties) == 0) {
			try {
				String msgId = message.getString("msgid");
				// 校验数据合法性
				JSONObject ck = PayValid.validPay(rebuildJSONArray(message.getJSONArray("datas")), msgId);
				if (ck != null) {
					if (ck.get("code").equals(ResponseType.ICCARD_NOT_FOUND.toString())) {
						// 如果是找不到iccard则向平台请求查找iccard
						// 向平台请求查询该iccard号
						JSONArray goodsObject = message.getJSONArray("datas");
						Map<String, String> params = getParams(goodsObject);
						serialnum = params.get("serialnum");
						JSONObject query = new JSONObject();
						query.put("cardno", params.get("cardno"));
						query.put("cardtype", Integer.valueOf(params.get("cardtype")));
						JSONObject cardInfo = rebuildJSON(queryIccardWithPlatform(query));
						if (cardInfo != null) {
							// 如果平台存在该iccard则将消息发送给平台做跨平台处理
							// 先持久化消费记录到当前中心
							for (int i = 0; i < goodsObject.size(); i++) {
								JSONObject goodsObj = JSONObject.fromObject(goodsObject.get(i));
								// 判断该卡是否需要验证支付密码
								if(Constant.MUSTCHECK == cardInfo.getInt("checkpasswd")){
									// 判断支付密码是否正确 
									if(cardInfo.getString("enpasswd").equals(goodsObj.getString("password"))){
										// 判断卡号和uuid是否一致
										if(cardInfo.getString("uuid").equals(goodsObj.getString("uuid"))){
											addSaleDetail(goodsObj);
										} else{
											return failMsg(message.get("msgid"), StringValues.NO_MATCH_UUID,ResponseType.UUID_NOT_MATCH.toString());
										}
									} else{
										return failMsg(message.get("msgid"), StringValues.PAYPASSWD_ERROR,ResponseType.PAY_PASSWORD_ERROR.toString());
									}
								} else{
									addSaleDetail(goodsObj);
								}
							}
							// 创建要发送的消费消息
							cardInfo = rebuildJSON(cardInfo);
							BigDecimal balance = new BigDecimal(cardInfo.getString("balance"));
							balance = balance.setScale(2,BigDecimal.ROUND_HALF_UP);
							Map<Object, Object> rsMap = createPayMsg(params.get("uuid"), params.get("cardno"),params.get("serialnum"),
									params.get("cardtype"),params.get("shopcode"),params.get("paydevice"),params.get("stime"),
									balance,Integer.valueOf(cardInfo.getInt("status")));
							// 判断是否进行消费操作
							if ((boolean) rsMap.get("ispay")) {
								String sendMsg = String.valueOf(rsMap.get("msg"));
								// 重新构建datas数据
								message.put("datas", sendMsg);
								// 添加接口标识
								message.put("api", Constant.PAY);
								// 追加appid和secretkey
								addAppidAndSecretkey(message);
								// 发送消息keyedMessage第一个参数是topic第二个参数就是发送的消息内容
								producer.send(new KeyedMessage<String, String>(
										TOPIC, String.valueOf(message)));
								log.info("###PayProducer:"+ String.valueOf(message) + ",time:" + BaseUtil.getDate());
								addMessage(message, TOPIC, Constant.SUCCESS,StringValues.SEND_SUCCESSFUL);
								return successMsg(message.get("msgid"));
							} else {
								//删除消费记录
								saleDetailDao.deleteBySerialNum(params.get("serialnum"));
								addMessage(message, TOPIC, Constant.FAIL,String.valueOf(rsMap.get("msg")));
								return failMsg(message.get("msgid"),String.valueOf(rsMap.get("msg")));
							}
						} else {
							// 如果不存在则返回错误信息
							return failMsg(message.get("msgid"), StringValues.ICCARD_NOT_FOUND,ResponseType.ICCARD_NOT_FOUND.toString());
						}
					} else {
						addMessage(message, TOPIC, Constant.FAIL, ck.getString("msg"));
						return ck.toString();
					}
				} else {
					JSONArray goodsObject = message.getJSONArray("datas");
					Map<String, String> params = getParams(goodsObject);
					// 持久化消费记录
					for (int i = 0; i < goodsObject.size(); i++) {
						JSONObject goodsObj = JSONObject.fromObject(goodsObject.get(i));
						addSaleDetail(goodsObj);
					}
					// 创建要发送的消费消息
					Map<Object, Object> rsMap = createSyncMsg(params.get("uuid"), params.get("cardno"),params.get("serialnum"),
							params.get("cardtype"),params.get("shopcode"), params.get("paydevice"),
							params.get("stime"));
					// 判断是否进行消费操作
					if ((boolean) rsMap.get("ispay")) {
						String sendMsg = String.valueOf(rsMap.get("msg"));
						// 重新构建datas数据
						message.put("datas", sendMsg);
						// 添加接口标识
						message.put("api", Constant.SYNC);
						// 追加appid和secretkey
						addAppidAndSecretkey(message);
						// 发送消息keyedMessage第一个参数是topic第二个参数就是发送的消息内容
						producer.send(new KeyedMessage<String, String>(TOPIC,String.valueOf(message)));
						log.info("###PayProducer:" + String.valueOf(message) + ",time:" + BaseUtil.getDate());
						addMessage(message, TOPIC, Constant.SUCCESS,StringValues.SEND_SUCCESSFUL);
						return successMsg(message.get("msgid"));

					} else {
						addMessage(message, TOPIC, Constant.FAIL,String.valueOf(rsMap.get("msg")));
						return failMsg(message.get("msgid"),String.valueOf(rsMap.get("msg")));
					}
				}
			} catch (Exception e) {
				//删除消费记录
				saleDetailDao.deleteBySerialNum(serialnum);
				addMessage(message, TOPIC, Constant.FAIL, e.toString());
				return failMsg(message.get("msgid"), e.toString());
			}
		} else {
			return failMsg(message.get("msgid"), StringValues.MESSAGE_SENDING_REPEAT);
		}
	}

	/**
	 * 获取必要参数用于拼装消息数据
	 * 
	 * @param jsonArray
	 * @return
	 */
	private Map<String, String> getParams(JSONArray jsonArray) {
		Map<String, String> params = new HashMap<>();
		// 给所需变量赋值
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject goodsObj = JSONObject.fromObject(jsonArray.get(i));
			if (!params.containsKey("sfrom")) {
				params.put("sfrom", goodsObj.getString("sfrom"));
			}
			if (!params.containsKey("serialnum")) {
				params.put("serialnum", goodsObj.getString("serialnum"));
			}
			if (!params.containsKey("cardtype")) {
				params.put("cardtype", goodsObj.getString("cardtype"));
			}
			if (!params.containsKey("uuid")) {
				params.put("uuid", goodsObj.getString("uuid"));
			}
			if (!params.containsKey("shopcode")) {
				params.put("shopcode", goodsObj.getString("shopcode"));
			}
			if (!params.containsKey("paydevice")) {
				params.put("paydevice", goodsObj.getString("paydevice"));
			}
			if (!params.containsKey("stime")) {
				params.put("stime", goodsObj.getString("stime"));
			}
			if (!params.containsKey("cardNo")) {
				params.put("cardno", goodsObj.getString("sfrom"));
			}
		}
		return params;
	}

	/**
	 * 构建发送的json数据  SYNC
	 * 
	 * @param uuid
	 * @param cardNo
	 * @param serialNum
	 * @return
	 */
	private Map<Object, Object> createSyncMsg(String uuid, String cardNo,
			String serialNum, String cardType, String shopCode,
			String payDevice, String payDate) {
		Map<Object, Object> rsMap = new HashMap<>();
		// 查找卡和卡中余额
		Map<Object, Object> query = new HashMap<>();
		query.put("iccardno", cardNo);
		query.put("card_type", cardType);
		Iccard iccard = iccardDao.selectByCondition(query);
		BigDecimal balance = iccard.getBalance();
		SaleDetailResultMap sdResultMap = saleDetailDao.sumRealCharges(serialNum);
		BigDecimal realCharges = sdResultMap.getCount();
		realCharges = realCharges.setScale(2, BigDecimal.ROUND_HALF_UP);
		BigDecimal result = null;
		// 判断卡状态是否可用
		if (iccard.getEnabled() == Constant.ACCOUNTACTIVATE) {
			// 余额充足则进行消费操作
			if (balance.compareTo(realCharges) == 1) {
				result = balance.subtract(realCharges);
				iccard.setBalance(result);
				iccardDao.updateByPrimaryKey(iccard);
				JSONObject data = new JSONObject();
				data.put("uuid", uuid);
				data.put("cardno", cardNo);
				data.put("cardtype", Integer.valueOf(cardType));
				data.put("balance", result);
				data.put("shopcode", shopCode);
				data.put("paydevice", payDevice);
				data.put("paydate", payDate);
				data.put("payno", serialNum);
				data.put("code", Constant.PAY_RESULT_CODE_SUCCESS);
				data.put("resultmessage", StringValues.PAY_SUCCESSFUL);
				rsMap.put("ispay", true);
				rsMap.put("msg", String.valueOf(data));
				return rsMap;
			}
		} else {
			// 余额不足则返回相应信息
			rsMap.put("ispay", false);
			rsMap.put("msg", StringValues.ACCOUNT_NOT_AVAILABLE);
			return rsMap;
		}
		// 余额不足则返回相应信息
		rsMap.put("ispay", false);
		rsMap.put("msg", "消费金额：" + realCharges + "元，大于卡上余额：" + balance + "元，余额不足，请充值后再消费。");
		return rsMap;
	}

	/**
	 * 跨中心数据构造方法
	 * 
	 * @param uuid
	 * @param cardNo
	 * @param serialNum
	 * @return
	 */
	private Map<Object, Object> createPayMsg(String uuid, String cardNo,
			String serialNum, String cardType, String shopCode,
			String payDevice, String payDate, BigDecimal balance, Integer status) {
		Map<Object, Object> rsMap = new HashMap<>();
		SaleDetailResultMap sdResultMap = saleDetailDao.sumRealCharges(serialNum);
		String goodsName = sdResultMap.getGoodsName();
		String goodsType = sdResultMap.getGoodsType();
		BigDecimal realCharges = sdResultMap.getCount();
		realCharges = realCharges.setScale(2, BigDecimal.ROUND_HALF_UP);
		// 判断卡状态是否可用
		if (status == Constant.ACCOUNTACTIVATE) {
			// 余额充足则进行消费操作
			if (balance.compareTo(realCharges) == 1) {
				JSONObject data = new JSONObject();
				data.put("uuid", uuid);
				data.put("cardno", cardNo);
				data.put("cardtype", Integer.valueOf(cardType));
				data.put("amount", realCharges);
				data.put("goodsname", goodsName);
				data.put("goodstype", goodsType);
				data.put("shopcode", shopCode);
				data.put("paydevice", payDevice);
				data.put("paydate", payDate);
				data.put("payno", serialNum);
				rsMap.put("ispay", true);
				rsMap.put("msg", String.valueOf(data));
				return rsMap;
			}
		} else {
			// 余额不足则返回相应信息
			rsMap.put("ispay", false);
			rsMap.put("msg", StringValues.ACCOUNT_NOT_AVAILABLE);
			return rsMap;
		}
		// 余额不足则返回相应信息
		rsMap.put("ispay", false);
		rsMap.put("msg", "消费金额：" + realCharges + "元，大于卡上余额：" + balance + "元，余额不足，请充值后再消费。");
		return rsMap;
	}

	/**
	 * json数据处理方法
	 * 
	 * @param message
	 * @return
	 */
	private void addSaleDetail(JSONObject goodsObj) throws Exception {
		SaleDetail saleDetail = createEntity(goodsObj);
		saleDetailDao.insert(saleDetail);
		sqlSession.commit();
	}

	/**
	 * 创建实体类
	 * 
	 * @param saleDetailData
	 * @return
	 * @throws Exception
	 */
	private SaleDetail createEntity(JSONObject saleDetailData) throws Exception {
		SaleDetail saleDetail = new SaleDetail();
		saleDetail.setUuid(saleDetailData.getString("uuid"));
		saleDetail.setPid(Integer.valueOf(saleDetailData.getString("pid")));
		saleDetail.setProduct(saleDetailData.getString("product"));
		saleDetail.setSprice(BigDecimal.valueOf(saleDetailData.getInt("sprice")));
		saleDetail.setSerialNum(saleDetailData.getString("serialnum"));
		saleDetail.setScount(saleDetailData.getInt("scount"));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date stime = sdf.parse(saleDetailData.getString("stime"));
		saleDetail.setStime(stime);
		saleDetail.setSfrom(saleDetailData.getString("sfrom"));
		saleDetail.setPtype(saleDetailData.getString("ptype"));
		saleDetail.setDiscount(Float.valueOf(saleDetailData.getString("discount")));
		// 构造以字符串内容为值的BigDecimal类型的变量bd
		BigDecimal ds = new BigDecimal(saleDetailData.getString("discountprice"));
		// 设置小数位数，第一个变量是小数位数，第二个变量是取舍方法(四舍五入)
		ds = ds.setScale(2, BigDecimal.ROUND_HALF_UP);
		saleDetail.setDiscountPrice(ds);
		BigDecimal rc = new BigDecimal(saleDetailData.getString("realcharges"));
		rc = rc.setScale(2, BigDecimal.ROUND_HALF_UP);
		saleDetail.setRealCharges(rc);
		BigDecimal cp = new BigDecimal(saleDetailData.getString("costprice"));
		cp = cp.setScale(2, BigDecimal.ROUND_HALF_UP);
		saleDetail.setCostPrice(cp);
		return saleDetail;
	}

	/**
	 * 跨地区消费
	 * 
	 * @param message
	 * @throws Exception
	 */
	public JSONObject dcPay(JSONObject goodsObj) {
		JSONObject response = new JSONObject();
		try {
			// 查找卡和卡中余额
			Map<Object, Object> query = new HashMap<>();
			query.put("iccardno", goodsObj.getString("cardno"));
			query.put("card_type", goodsObj.getString("cardtype"));
			Iccard iccard = iccardDao.selectByCondition(query);
			BigDecimal balance = iccard.getBalance();
			// 计算余额并更新
			BigDecimal amount = new BigDecimal(goodsObj.getString("amount"));
			amount = amount.setScale(2, BigDecimal.ROUND_HALF_UP);
			response = createPayResult(goodsObj);
			// 判断ICCARD是否可用
			if (iccard.getEnabled() == Constant.ACCOUNTACTIVATE) {
				// 判断余额是否充足
				if (balance.compareTo(amount) == 1) {
					// 余额充足则扣除余额
					BigDecimal result = balance.subtract(amount);
					iccard.setBalance(result);
					// 交易成功，构造成功结果并返回
					response.put("balance", result);
					response.put("code", Constant.PAY_RESULT_CODE_SUCCESS);
					response.put("resultmessage", StringValues.PAY_SUCCESSFUL);
					// 将计算后余额追加进原始数据中
					goodsObj.put("balance", result);
					// 交易成功向平台发送同步消息
					JSONObject message = createDCMessage(goodsObj);
					// 追加appid和secretkey
					addAppidAndSecretkey(message);
					// 发送消息keyedMessage第一个参数是topic第二个参数就是发送的消息内容
					producer.send(new KeyedMessage<String, String>(TOPIC,String.valueOf(message)));
					// 消息发送成功后才更新数据库
					iccardDao.updateByPrimaryKey(iccard);
					addDCSaleDetail(goodsObj);
					log.info("###PayProducer:" + String.valueOf(message) + ",time:" + BaseUtil.getDate());
					addMessage(message, TOPIC, Constant.SUCCESS,StringValues.SEND_SUCCESSFUL);
					return response;
				} else {
					// 余额不足返回PAY_RESULT_CODE_INSUFFICENT
					response.put("code", Constant.PAY_RESULT_CODE_INSUFFICENT);
					response.put("resultmessage", StringValues.PAY_INSUFFICENT);
					return response;
				}
			} else {
				// 卡不可用返回PAY_RESULT_CODE_DENY
				response.put("code", Constant.PAY_RESULT_CODE_DENY);
				response.put("resultmessage", StringValues.PAY_DENY);
				return response;
			}

		} catch (Exception e) {
			e.printStackTrace();
			// 系统异常 返回PAY_RESULT_CODE_ERROR及响应异常信息
			response.put("code", Constant.PAY_RESULT_CODE_ERROR);
			response.put("resultmessage", e.toString());
			return response;
		}

	}
	
	/**
	 * 构造跨平台消费message
	 * @param datas
	 * @return
	 */
	private JSONObject createDCMessage(JSONObject datas){
		JSONObject message = new JSONObject();
		message.put("msgtype", MsgType.pay);
		UUID msgid = UUID.randomUUID();
		message.put("msgid", msgid);
		message.put("datas", datas);
		message.put("createtime",BaseUtil.getDate());
		message.put("api", Constant.SYNC);
		return message;
	}

	/**
	 * 创建跨平台消费支付结果
	 * 
	 * @param goodsObj
	 * @return
	 */
	private JSONObject createPayResult(JSONObject goodsObj) {
		JSONObject data = new JSONObject();
		data.put("uuid", goodsObj.getString("uuid"));
		data.put("cardno", goodsObj.getString("cardno"));
		data.put("cardtype", goodsObj.getInt("cardtype"));
		data.put("shopcode", goodsObj.getString("shopcode"));
		data.put("paydevice", goodsObj.getString("paydevice"));
		data.put("paydate", goodsObj.getString("paydate"));
		data.put("payno", goodsObj.getString("payno"));
		return data;
	}

	/**
	 * 持久化跨平台消费明细
	 * 
	 * @param goodsObj
	 * @throws Exception
	 */
	private void addDCSaleDetail(JSONObject goodsObj) throws Exception {
		SaleDetail saleDetail = createDCPayEntity(goodsObj);
		saleDetailDao.insert(saleDetail);
		sqlSession.commit();
	}

	/**
	 * 创建跨平台消费明细实体
	 * 
	 * @param saleDetailData
	 * @return
	 */
	private SaleDetail createDCPayEntity(JSONObject saleDetailData) {
		SaleDetail saleDetail = new SaleDetail();
		saleDetail.setUuid(saleDetailData.getString("uuid"));
		saleDetail.setProduct(saleDetailData.getString("goodsname"));
		saleDetail.setSerialNum(saleDetailData.getString("payno"));
		saleDetail.setSfrom(saleDetailData.getString("cardno"));
		saleDetail.setPtype(saleDetailData.getString("goodstype"));
		BigDecimal rc = new BigDecimal(saleDetailData.getString("amount"));
		rc = rc.setScale(2, BigDecimal.ROUND_HALF_UP);
		saleDetail.setRealCharges(rc);
		return saleDetail;
	}
	
	/**
	 * 充值处理类
	 * @param message
	 * @return
	 */
	private String rechargeProduce(JSONObject message) {
		try {
			String msgId = message.getString("msgid");
			// 校验数据合法性
			JSONObject ck = PayValid.validRecharge(rebuildJSON(message.getJSONObject("datas")), msgId);
			if (ck != null) {
				if (ck.get("code").equals(ResponseType.ICCARD_EXIST.toString()) 
						|| ck.get("code").equals(ResponseType.ICCARD_NOT_FOUND.toString()) 
						|| ck.get("code").equals(ResponseType.SYSTEM_ERROR.toString())
						|| ck.get("code").equals(ResponseType.DATA_FORMAT_ERROR.toString())) {
					addMessage(message,TOPIC,Constant.FAIL, ck.getString("msg"));
					// 校验不通过则返回信息
					return ck.toString();
				} else {
					// 本地没有对应的iccard则向平台请求，并返回响应信息给客户端
					// 这里向平台发送请求，检查iccard是否存在
					JSONObject params = new JSONObject();
					params.put("cardno", message.getJSONObject("datas").getString("cardno"));
					params.put("cardtype", message.getJSONObject("datas").getInt("cardtype"));
					JSONObject cardInfo = rebuildJSON(queryIccardWithPlatform(params));
					if (cardInfo!=null) {
						if(cardInfo.getInt("status")==0){
							// 判断卡号和uuid是否一致
							if(cardInfo.getString("uuid").equals(message.getJSONObject("datas").getString("uuid"))){
								// 获取充值金额
								BigDecimal amount = new BigDecimal(message.getJSONObject("datas").getString("amount"));
								amount = amount.setScale(2, BigDecimal.ROUND_HALF_UP);
								// 重构消息
								String datas = buildRechargeMsg(message,amount,null);
								message.put("datas", datas);
								message.put("api", Constant.PAY);
								// 追加appid和secretkey
								addAppidAndSecretkey(message);
								// 发送消息keyedMessage第一个参数是topic第二个参数就是发送的消息内容
								producer.send(new KeyedMessage<String, String>(TOPIC, message.toString()));
								log.info("###UpdateProducer:" + message.toString() + ",time:" + BaseUtil.getDate());
								addMessage(message,TOPIC,Constant.SUCCESS, StringValues.SEND_SUCCESSFUL);
								return successMsg(message.get("msgid"));
							} else{
								return failMsg(message.get("msgid"), StringValues.NO_MATCH_UUID,ResponseType.DATA_FORMAT_ERROR.toString());
							}
						}else{
							return failMsg(message.get("msgid"),StringValues.ACCOUNT_NOT_AVAILABLE,ResponseType.ICCARD_UNABLE.toString());
						}
					}else{
						// 如果平台也没有该iccard返回错误信息
						return failMsg(message.get("msgid"),StringValues.USER_NOT_EXIST,ResponseType.USER_NOT_EXIST.toString());
					}
				}
			} else {
				Map<String, Object> params = new HashMap<>();
				params.put("status", Constant.SUCCESS);
				params.put("message_id", message.get("msgid"));
				if(messageDao.selectByParam(params)==0){
					Map<Object,Object> query = new HashMap<>();
					query.put("iccardno", message.getJSONObject("datas").getString("cardno"));
					query.put("card_type", message.getJSONObject("datas").getString("cardtype"));
					Iccard iccard = iccardDao.selectByCondition(query);
					if (iccard.getEnabled() == Constant.ACCOUNTACTIVATE){
						// 获得本中心查询到的卡中余额
						BigDecimal balance = iccard.getBalance();
						// 获取充值金额
						BigDecimal amount = new BigDecimal(message.getJSONObject("datas").getString("amount"));
						amount = amount.setScale(2, BigDecimal.ROUND_HALF_UP);
						// 计算充值结果
						BigDecimal reuslt = balance.add(amount);
						//重构datas部分
						String datas = buildRechargeMsg(message,amount,reuslt);
						message.put("datas", datas);
						message.put("api", Constant.SYNC);
						// 追加appid和secretkey
						addAppidAndSecretkey(message);
						// 发送消息keyedMessage第一个参数是topic第二个参数就是发送的消息内容
						producer.send(new KeyedMessage<String, String>(TOPIC, message.toString()));
						// 消息发送成功后更新本地数据库
						iccardDao.updateBalanceByCardNo(reuslt.toString(), message.getJSONObject("datas").getString("cardno"));
						log.info("###AccountProducer:" + message.toString() + ",time:" + BaseUtil.getDate());
						addMessage(message,TOPIC,Constant.SUCCESS, StringValues.SEND_SUCCESSFUL);
						return successMsg(message.get("msgid"));
					} else {
						return failMsg(message.get("msgid"),StringValues.ACCOUNT_NOT_AVAILABLE);
					}
				}else{
					return failMsg(message.get("msgid"),StringValues.MESSAGE_SENDING_REPEAT);
				}
			}
		} catch (Exception e) {
			addMessage(message,TOPIC,Constant.FAIL, e.toString());
			return failMsg(message.get("msgid"), e.toString());
		}
	}
	
	/**
	 * 重构充值消息数据
	 * @param message
	 * @param result
	 * @return
	 */
	private String buildRechargeMsg(JSONObject message,BigDecimal amount,BigDecimal result){
		JSONObject datas = message.getJSONObject("datas");
		JSONObject send = new JSONObject();
		send.put("uuid", datas.getString("uuid"));
		send.put("cardno", datas.getString("cardno"));
		send.put("cardtype", datas.getInt("cardtype"));
		send.put("amount", amount);
		send.put("balance", result);
		send.put("goodsname", Constant.GOODSNAME);
		send.put("goodstype", Constant.GOODSTYPE);
		send.put("shopcode", datas.getString("shopcode"));
		send.put("paydevice", datas.getString("paydevice"));
		send.put("paydate", datas.getString("paydate"));
		return send.toString();
	}
	
	/**
	 * 跨平台充值处理方法
	 * @param message
	 * @return
	 */
	public JSONObject dcRecharge(JSONObject message){
		JSONObject datasResult = new JSONObject();
		try {
			datasResult = JSONObject.fromObject(buildDCRechargeMsg(message));
			Map<Object,Object> query = new HashMap<>();
			query.put("iccardno", message.getJSONObject("datas").getString("cardno"));
			query.put("card_type", message.getJSONObject("datas").getString("cardtype"));
			Iccard iccard = iccardDao.selectByCondition(query);
			if (iccard.getEnabled() == Constant.ACCOUNTACTIVATE){
				// 获得本中心查询到的卡中余额
				BigDecimal balance = iccard.getBalance();
				// 获取充值金额
				BigDecimal amount = new BigDecimal(message.getJSONObject("datas").getString("amount"));
				amount = amount.setScale(2, BigDecimal.ROUND_HALF_UP);
				// 计算充值结果
				BigDecimal result = balance.add(amount);
				//重构datas部分
				String datas = buildRechargeMsg(message,amount,result);
				message.put("datas", datas);
				message.put("api", Constant.SYNC);
				// 追加appid和secretkey
				addAppidAndSecretkey(message);
				// 发送消息keyedMessage第一个参数是topic第二个参数就是发送的消息内容
				producer.send(new KeyedMessage<String, String>(TOPIC, message.toString()));
				// 消息发送成功后更新本地数据库
				iccardDao.updateBalanceByCardNo(result.toString(), message.getJSONObject("datas").getString("cardno"));
				log.info("###AccountProducer:" + message.toString() + ",time:" + BaseUtil.getDate());
				addMessage(message,TOPIC,Constant.SUCCESS, StringValues.SEND_SUCCESSFUL);
				datasResult.put("balance", result);
				datasResult.put("code", Constant.PAY_RESULT_CODE_SUCCESS);
				datasResult.put("resultmessage", StringValues.RECHARGE_SUCCESSFUL);
				return datasResult;
			} else {
				datasResult.put("code", Constant.PAY_RESULT_CODE_DENY);
				datasResult.put("resultmessage", StringValues.RECHARGE_FAIL);
				return datasResult;
			}
		} catch (Exception e) {
			datasResult.put("code", Constant.PAY_RESULT_CODE_ERROR);
			datasResult.put("resultmessage", e.toString());
			return datasResult;
		}
	
	}
	
	/**
	 * 创建跨地区充值结果
	 * @param message
	 * @return
	 */
	private String buildDCRechargeMsg(JSONObject message){
		JSONObject datas = message.getJSONObject("datas");
		JSONObject send = new JSONObject();
		send.put("uuid", datas.getString("uuid"));
		send.put("cardno", datas.getString("cardno"));
		send.put("cardtype", datas.getInt("cardtype"));
		send.put("shopcode", datas.getString("shopcode"));
		send.put("paydevice", datas.getString("paydevice"));
		send.put("paydate", datas.getString("paydate"));
		send.put("payno", datas.getString("payno"));
		return send.toString();
	}
}